package org.windblog.core.servlet.page;

import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.windblog.core.PageService;
import org.windblog.core.entity.Page;

import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class AddPageServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String title = req.getParameter("title").trim();
		String content = req.getParameter("content");
		String order = req.getParameter("order");
		int priority = 0;
		if (order != null)
			priority = Integer.parseInt(order);
		String parent = req.getParameter("parent");

		Page page = new Page();
		page.setTitle(title);
		page.setAuthor(UserServiceFactory.getUserService().getCurrentUser()
				.getEmail());
		page.setPriority(priority);
		page.setDate(new Date());
		page.setRoot(false);
		page.setContent(content);

		PageService.setPage(page);

		if (parent == null || parent.equals("")) {
			Page root = PageService.getRoot();
			root.addChild(page);
		} else {
			Page pPage = PageService.getPage(parent);
			if(pPage==null)
				resp.sendRedirect("/admin/editPages.jsp?message=1");
			pPage.addChild(page);
		}
		resp.sendRedirect("/admin/editPages.jsp?message=2");

	}

}
